package com.java.service.impl;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.java.dao.AdvertisersAccountMapper;
import com.java.model.AdvertisersAccount;
import com.java.model.AdvertisersWallet;
import com.java.model.Result;
import com.java.service.AdvertisersAccountService;
import darabonba.core.client.ClientOverrideConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@Service
public class AdvertisersAccountServiceImpl implements AdvertisersAccountService {

    @Autowired
    private AdvertisersAccountMapper advertisersAccountMapper;
    @Autowired
    private AdvertisersAccountService advertisersAccountService;


    int i = 0;

    @Override
    public Result modify(AdvertisersAccount advertisersAccount) {
        advertisersAccountMapper.modify(advertisersAccount);
        return Result.success();
    }

    @Override
    public Result remove(int[] ids) {
        return null;
    }


    @Override
    public Result list(AdvertisersAccount advertisersAccount) {
        PageHelper.startPage(advertisersAccount.getPageNum(), advertisersAccount.getPageSize()); // 提醒page在显示哪一页的数据和要显示多少条数据
        List<AdvertisersAccount> list = advertisersAccountMapper.list(advertisersAccount);
        PageInfo<AdvertisersAccount> pageInfo = new PageInfo<>(list);

        return Result.success(pageInfo.getList(), pageInfo.getTotal());
    }

    @Override
    public Result get(int id) {
        AdvertisersAccount advertisersAccount = advertisersAccountMapper.get(id);
        return Result.success(advertisersAccount, null);
    }

    /**
     * 短信验证
     * @param phoneNum
     * @return
     */
    @Override
    public Result message(String phoneNum) {
        Random random = new Random(); // 用于作为随机数的验证码
        i = random.nextInt(9999 - 1000 + 1) + 1000;
        System.out.println(i);

        // Configure Credentials authentication information, including ak, secret, token
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId("LTAI5t8g5krDi9M2ewcM1pjr") // accessKeyId值
                .accessKeySecret("oT5qZ1wPbMigmIWmgDQvhqF55KNhzZ") //accessKeySecret值
                //.securityToken("<your-token>") // use STS token
                .build());

        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                .region("cn-hangzhou") // Region ID
                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                .credentialsProvider(provider)
                //.serviceConfiguration(Configuration.create()) // Service-level configuration
                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();

        // Parameter settings for API request
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName("阿里云短信测试")
                .templateCode("SMS_154950909")
                .phoneNumbers(phoneNum)
                .templateParam("{\"code\":\"" + i +"\"}")
                // Request-level configuration rewrite, can set Http request parameters, etc.
                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();

        // Asynchronously get the return value of the API request
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        // Synchronously get the return value of the API request
        SendSmsResponse resp = null;
        try {
            resp = response.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println(new Gson().toJson(resp));
        // Asynchronous processing of return values
        /*response.thenAccept(resp -> {
            System.out.println(new Gson().toJson(resp));
        }).exceptionally(throwable -> { // Handling exceptions
            System.out.println(throwable.getMessage());
            return null;
        });*/

        // Finally, close the client
        client.close();

        return Result.success();
    }

    @Override
    public Result save(AdvertisersAccount advertisersAccount) {
        if (advertisersAccount.getPhoneCode().equals(i)) { // 判断验证码是否一致
            Date date = new Date(); // 获取时间
            SimpleDateFormat dateFormat= new SimpleDateFormat("yyyyMMdd");
            advertisersAccount.setUsername("WIVF" + dateFormat.format(date));
            advertisersAccount.setCompanyTime(date);

            advertisersAccountMapper.save(advertisersAccount);
            return Result.error("注册成功");
        } else {
            return Result.error("验证码不一致");
        }
    }

    @Override
    public Result updateStatus(int[] ids, String status) {
        for (Integer id : ids) {
            AdvertisersAccount advertisersAccount = new AdvertisersAccount();
            advertisersAccount.setId(id);
            advertisersAccount.setStatus(status);
            advertisersAccountMapper.updateStatus(advertisersAccount);
        }
        return Result.success();
    }

    @Override
    public Result wallet(AdvertisersAccount advertisersAccount) {
        PageHelper.startPage(advertisersAccount.getPageNum(), advertisersAccount.getPageSize()); // 提醒page在显示哪一页的数据和要显示多少条数据
        List<AdvertisersAccount> list = advertisersAccountMapper.wallet(advertisersAccount);
        PageInfo<AdvertisersAccount> pageInfo = new PageInfo<>(list);

        return Result.success(pageInfo.getList(), pageInfo.getTotal());
    }

    @Override
    public AdvertisersAccount walletList(Integer id) {
        return advertisersAccountMapper.walletList(id);
    }

    @Override
    public AdvertisersAccount recharge(int id) {
        return advertisersAccountMapper.recharge(id);
    }

    @Override
    public Result money(AdvertisersWallet advertisersWallet) {
        advertisersAccountMapper.money(advertisersWallet);
        return Result.success();
    }

    @Override
    public Result frozen(AdvertisersWallet advertisersWallet) {
        advertisersAccountMapper.frozen(advertisersWallet);
        return Result.success();
    }

    @Override
    public Result addRecharge(AdvertisersWallet advertisersWallet) {
        advertisersAccountMapper.addRecharge(advertisersWallet);
        return Result.success();
    }

    /**
     * 广告主登录
     * @param advertisersAccount
     * @param request
     * @return
     */
    @Override
    public Result advertisingLogin(AdvertisersAccount advertisersAccount, HttpServletRequest request) {

        AdvertisersAccount advertisersAccount1 = advertisersAccountMapper.advertisingLogin(advertisersAccount);
        if (advertisersAccount1 != null) {
            HttpSession session = request.getSession();
            session.setAttribute("advertisersAccount", advertisersAccount1);

            return Result.success();
        }

        return Result.error("用户名或密码错误");
    }

    @Override
    public Result advertisersWalletModify(AdvertisersWallet advertisersWallet) {
        advertisersAccountMapper.advertisersWalletModify(advertisersWallet);
        return Result.success();
    }

    /**
     * 广告主金额充值
     * @param advertisersAccount
     * @return
     */
    @Override
    public Result addAmount(AdvertisersAccount advertisersAccount) {
        advertisersAccountMapper.addAmount(advertisersAccount);
        return Result.success();
    }
}
